package utils

import (
	"bytes"
	"crypto/tls"
	"io"
	"io/ioutil"
	"local.public/innerpkg/logger"
	"net/http"
	"net/url"
)

func ThirdPartyHttpsGet(sUrl string, head map[string]string, params map[string]string) ([]byte, error) {
	getParams := url.Values{}
	for key, value := range params {
		getParams.Add(key, value)
	}
	sParams := getParams.Encode()
	logger.Debug("params", sParams)
	req, _ := http.NewRequest("GET", sUrl+"?"+sParams, nil)
	for key, value := range head {
		req.Header.Add(key, value)
	}

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true, //跳过验证服务端证书
			MinVersion:         tls.VersionTLS10,
			MaxVersion:         tls.VersionTLS12,
		},
	}

	client := &http.Client{Transport: tr}

	res, err1 := client.Do(req)
	if err1 != nil {
		logger.Debug("向第三方https请求失败!", err1)
		return nil, err1
	}

	defer res.Body.Close()
	retBody, err2 := ioutil.ReadAll(res.Body)
	if err2 != nil {
		logger.Debug("读取第三方https响应失败!", err2)
		return nil, err2
	}
	return retBody, nil
}

func ThirdPartyHttpsPost(url string, head map[string]string, body []byte) ([]byte, error) {
	var payload io.Reader
	payload = bytes.NewReader(body)
	req, _ := http.NewRequest("POST", url, payload)

	for key, value := range head {
		req.Header.Add(key, value)
	}

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true, //跳过验证服务端证书
			MinVersion:         tls.VersionTLS10,
			MaxVersion:         tls.VersionTLS12,
		},
	}

	client := &http.Client{Transport: tr}

	res, err1 := client.Do(req)
	if err1 != nil {
		logger.Debug("向第三方https请求失败!", err1)
		return nil, err1
	}

	defer res.Body.Close()
	retBody, err2 := ioutil.ReadAll(res.Body)
	if err2 != nil {
		logger.Debug("读取第三方https响应失败!", err2)
		return nil, err2
	}
	return retBody, nil
}
